/**
* @description: 现场打卡 （施工、监理）
* @author: zhangxia
* @date:
**/
<template>
	<view class="task-monitor-main">
		<nav-bar class="header" back title="施工现场" @goBack="goBack"></nav-bar>
		<view class="spot-content">
			<view class="basic-info">
          <van-form ref="ruleForm">
            <van-cell-group>
              <van-field disabled v-model="engName" label="工程名称"
                         type="textarea" required autosize  rows="1"
                         :rules="[{ required: true}]" placeholder="请选择" right-icon="arrow" input-align="right"
                         @click-right-icon="handleSelect('engName')"/>
              <van-field disabled v-model="siteName" label="站点名称" required input-align="right"
                         :rules="[{ required: true}]" placeholder="请选择" right-icon="arrow"
                         @click-right-icon="handleSelect('siteName')"/>
              <van-field disabled v-model="sceneName" label="施工现场" required input-align="right"
                         :rules="[{ required: true}]" placeholder="请选择" right-icon="arrow"
                         @click-right-icon="handleSelect('scene')" v-if="sceneColumns.length !== 0"/>
              <van-field v-model="sceneName"  name="sceneName" label="施工现场" placeholder="请输入施工现场"
                         input-align="right" error-message-align="right"
                         v-if="sceneColumns.length === 0"/>
                         <!-- required  :rules="[{ required: true,trigger:'onChange', message: '' }]"-->
            </van-cell-group>
          </van-form>
			</view>
      <view class="map-content" v-if="isShoeMap">
        <view class="map-top">
          <text></text>
          <text class="orientation" @click="getOrientation()">定位</text>
        </view>
        <view id="map_holder"></view>
      </view>
	  <!-- 暂时不需要此功能 -->
      <!-- <plateTitle title="签到图片" :isRequired="true" class="plate-title"></plateTitle> -->
     <!-- <view class="overall-materials">
        <view class="image-list">
          <view class="upload-button" v-for="(imgItem, imgIndex) in fileList" :key="imgIndex"
                @click.stop="imageHandle(imgIndex,imgItem,'CHOOSE')">
            <view v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgIndex,imgItem, 'DELETE')">
              ×</view>
            <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgIndex,imgItem, 'PREVIEW')">
          </view>
        </view>
      </view> -->
      <view class="circle-wrap">
        <view class="circle-conent"  @click="goApproval">
          创建现场
        </view>
      </view>
		</view>
		<footer v-if="isShoeMap">
			<van-button block native-type="submit" @click="goApproval">{{ btnText }}</van-button>
		</footer>
    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe>
        <div v-for="(image, index) in files" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
    <!-- 选择工程名称 -->
    <van-popup v-model="showSelectProject" position="bottom">
      <van-picker :title="pickerName" ref="typePicker" show-toolbar :columns="projectNameColumns"
                  @confirm="onConfirm" @cancel="showSelectProject = false" />
    </van-popup>
    <!-- 选择站点名称   -->
    <van-popup v-model="showSelectSite" position="bottom">
      <van-picker :title="pickerName" ref="typePicker" show-toolbar :columns="siteNameColumns"
                  @confirm="onConfirmSite" @cancel="showSelectSite = false" />
    </van-popup>
		<!--现场信息选择器-->
		<van-popup v-model="showPicker" position="bottom">
			<van-picker :title="pickerName" ref="typePicker" show-toolbar :columns="sceneColumns"
				@confirm="onConfirmfiled" @cancel="showPicker = false" />
		</van-popup>
	</view>
</template>
<script>
import config from "../../../common/config";
import navBar from "../../../components/common/nav-bar";
import plateTitle from '../common/plateTitle.vue'
import {Dialog, Toast} from "vant"
import {mapGetters} from "vuex";
import wx from '../../../static/common_js/jweixin_1.0.0'
import axios from "axios";
export default {
  name: 'spotClocking',
  components: { navBar,plateTitle},
  props: {},
  data() {
    return {
      baseUrl:'',
      jd:'',
      wd:'',
      SCENE_LOCATION:'',
      engName:'',
      engId:'',
		  siteName:'',
      siteId:'',
		  sceneName:'',
      sceneId:'',
      showSelectProject: false,
      showSelectSite: false,
      projectNameColumns:[],
      siteNameColumns:[],
		  showPicker:false,
		  sceneColumns:[],
		  pickerName:"",
      showPreview:false,
      fileList:[
        {
          File: null,
          img: '',
          fl: ''
        },
      ],
      fileId:'',
      files:[],
      delList:[],
      isShoeMap: false
	};
  },
  computed: {
    ...mapGetters(['userData']),
    btnText() {
		return '确认'
      // if(this.sceneColumns.length == 0) {
      //   return '考勤打卡'
      // }else {
      //   return '签到'
      // }
    }
  },
  watch: {},
  onLoad() {
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl+'/txgcgk/profile/mapicon.png';
      // this.baseUrl = 'http:/192.168.0.127:18001'+'/txgcgk/profile/mapicon.png';
    })
	  this.getProjectName()
    this.initChart()
  },
  methods: {
    initChart () {
      if (typeof epgis === 'undefined') {
        // eslint-disable-next-line no-undef
        var cssurl = this.$Config.gisUrl
        // eslint-disable-next-line no-undef
        var jsurl = this.$Config.gisUrljs
        this.loadCss(cssurl, () => {
          this.loadJS(jsurl, () => {
            this.initMap(this.baseUrl)
          })
        })
      } else {
        this.initMap()
      }
    },
    loadJS (url, callback) {
      // eslint-disable-next-line one-var
      var script = document.createElement('script'),
          fn = callback || function () { }
      script.type = 'text/javascript'
      // IE
      if (script.readyState) {
        script.onreadystatechange = function () {
          if (script.readyState === 'loaded' || script.readyState === 'complete') {
            script.onreadystatechange = null
            fn()
          }
        }
      } else {
        // 其他浏览器
        script.onload = function () {
          fn()
        }
      }
      script.src = url
      document.getElementsByTagName('head')[0].appendChild(script)
    },
    loadCss (url, fn) {
      // var head = document.getElementsByTagName('head')[0];
      var link = document.createElement('link')
      link.type = 'text/css'
      link.rel = 'stylesheet'
      if (link.readyState) {
        link.onreadystatechange = function () {
          if (link.readyState === 'loaded' || link.readyState === 'complete') {
            link.onreadystatechange = null

            fn()
          }
        }
      } else {
        // 其他浏览器

        link.onload = function () {
          fn()
        }
      }
      link.href = url
      document.getElementsByTagName('head')[0].appendChild(link)
    },
    initMap (baseUrl) {
      // eslint-disable-next-line no-undef
      epgis.tokenTask
          .login('d90b195097243a32bdd90bfe87f608b9', '414deabb87fc3fb2af81874250eb0a1a')
          .then(function () {
            // eslint-disable-next-line no-undef
            window.PSMAP = new epgis.Map({
              container: 'map_holder',
              // style: _this.theme === 'dark' ? 'aegis://styles/aegis/StreetsDark' : 'aegis://styles/aegis/Streets',
              style: 'aegis://styles/aegis/Streets',
              zoom: 5,
              // maxZoom: 7.9,
              dragPan: true, // 地图是否可通过鼠标拖拽平移，默认为true
              doubleClickZoom: true, // 是否支持双击放大地图
              scrollZoom: true, // 是是否缩放
              center: [112.27293603983162,37.947509995760996], //山西金纬度
              // center: [116.76, 37.05],
              // center: [119.86868, 30.77642],
              localIdeographFontFamily: 'Microsoft YoHei'
            })
            PSMAP.on("load", function (e) {
              console.log(baseUrl,'rthis')
              //var serviceTask = new epgis.ServiceTask();
              //
              //先建立好画选中点的图层，然后之后再设置位置和移除
              PSMAP.loadImage((baseUrl),function (error, image) {
                if (error) throw error;
                PSMAP.addImage("poi", image);
                PSMAP.addLayer({
                  'id': "choicePoi",
                  "type": "symbol",
                  "source": {
                    "type": "geojson",
                    "data": {
                      'type': "FeatureCollection",
                      "features": []
                    }
                  },
                  "layout": {
                    "icon-image": "poi",
                    "icon-size": 0.5,
                    "icon-anchor": "bottom",
                    //"icon-offset":[0,0],
                    "icon-ignore-placement": true,
                  }
                });
              });
            });
            PSMAP.addControl(new epgis.ScaleControl({
              maxWidth: 80,
              unit: 'metric'
            }), 'bottom-left');

          PSMAP.on("click", function (e) {
              var features = PSMAP.queryRenderedFeatures(e.point);
              console.log(features);
              console.log(e);
            });
          })
          .catch(err => {
            console.log(err)
          })
    },
    getOrientation() {
      const that_ = this
      wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function (res) {
          that_.wd = res.latitude
          that_.jd = res.longitude
          uni.request({
            url: 'https://restapi.amap.com/v3/geocode/regeo',
            data:{
              // 申请web服务API类型KEY
              key: '0ae40dcfc5916391f7fdb17939737c81',
              location: `${that_.jd},${that_.wd}`
            },
            success: function (res) {
              console.log('得到的信息是', res);
              this.SCENE_LOCATION = res.data.regeocode.formatted_address
              const convertTask = new epgis.ConvertTask();
              let cords = [that_.jd +','+ that_.wd]
              console.log(cords)
              convertTask.convertCoord([cords],{
                from: 1,
              }).then(function (result){
                //画点,且控制面板出现与否
                PSMAP.getSource("choicePoi").setData({
                  'type': "FeatureCollection",
                  'features': [{
                    'type': 'Feature',
                    'geometry': {
                      'type': 'Point',
                      'coordinates': result[0]
                    }
                  }]
                });
                PSMAP.easeTo({
                  center: result[0],
                  zoom: 18
                });
              })
            }
          })
        },fail:function(res){
          console.log("getLocation end",res);
        }
      });

    },
	  goBack() {
	    uni.navigateTo({
	      url: '/pages/communicationControl/index/index'
	    })
	  },
    // 获取工程名称
    getProjectName() {
      let params = {
        userId: this.userData.USERID,
      }
      this.$apiRequest.gcgkApi.getEngListByUserId(params).then(res => {
        this.projectNameColumns = res.data.map(item => {
		  if(item.SELECTDEFAULT === '1'){
			  this.engName = item.ENG_NAME;
			  this.engId = item.OBJ_ID
			  if(this.engId !== null){
			  	this.getSiteName()
			  }
		  }
          return {
            text: item.ENG_NAME,
            value: item.OBJ_ID,
          };
        })
      })
    },
    // 获取站点名称
    getSiteName() {
      let params = {
        engId: this.engId,
		    userId:this.userData.USERID
      }
      this.$apiRequest.gcgkApi.getEngSiteList(params).then(res => {
        this.siteNameColumns = res.data.map(item => {
			if(item.selectDefault === '1'){
			  this.siteName = item.stationName;
			  this.siteId = item.stationId
			}
          return {
            text: item.stationName,
            value: item.stationId,
          };
        })
      })
    },
    // 获取现场信息
    getSceneName() {
      let params = {
        ENG_ID: this.engId,
        STATION_ID: this.siteId
      }
      this.$apiRequest.gcgkApi.queryTxgcgkdtxc(params).then(res => {
        this.sceneColumns = res.data.map(item => {
          return {
            text: item.SCENE_NAME,
            value: item.OBJ_ID,
          };
        })
        console.log(this.sceneColumns,'rthis')
      })
    },
    // 提交信息
    submit() {
      let param = new FormData()
      this.fileList.forEach((item, index) => {
        if(item.File !== null) {
          // console.log( `requests[${index}].file`,'file')
          // console.log( `requests[${index}].jlid`,'jlid')
          // console.log( `requests[${index}].fl`,'fl')
          param.append(`requests[${index}].file`, item.File)
          param.append(`requests[${index}].jlid`, this.fileId)
          param.append(`requests[${index}].fl`, item.fl)
        }
      })
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          // Authorization: uni.getStorageSync('token') || ''
        }
      }
      let url = "";
      // #ifndef IGW
      url = "/ap/txgcgk/api/file/uploads";
      // #endif
      // #ifdef IGW
      url = `${this.baseUrl}/txgcgk/api/file/uploads`
      // #endif
      axios.post(url, param, config).then(res => {
        Toast.clear();
        if (res.data.code == 0) {
          uni.navigateTo({
            url: '/pages/communicationControl/index/index'
          })
          Toast('提交成功');
        } else {
          Toast.clear();
          Toast('提交失败');
        }
      })
    },
    goApproval() {
      this.$refs.ruleForm.validate().then(() => {
        let params = {
          SCENE_NAME: this.sceneName,
          SCENE_LOCATION: this.SCENE_LOCATION,
          ENG_ID: this.engId,
          ENG_NAME: this.engName,
          HEAD_ID: this.userData.USERID,
          HEAD_NAME: this.userData.USERNAME,
          XZB: this.jd,
          YZB: this.wd,
          STATION_ID: this.siteId,
          STATION_NAME: this.siteName,
          DEPTID: this.userData.DEPTID,
          ROLEID: this.userData.ROLEID,
          xcid:this.sceneId
        }
		//暂不需要图片上传功能
        // if(this.fileList[0].File == null) {
        //   Toast('请完善拍照');
        // }else {
          Dialog.confirm({
            message: "是否确认提交？",
          }).then(() => {
            this.$apiRequest.gcgkApi.insertTxgcgkdtxc(params).then(res => {
              if(res.code == 0) {
                this.fileId = res.data
				Toast('提交成功');
				//暂不需要此功能 上传图片
                // this.submit()
              }else {
                Toast(res.msg);
              }
            })
          })
        // }
      }).catch(() => {
        Toast('请完善内容');
      })

    },
    // 获取
	  handleSelect(type){
		  if(type ==='engName'){
			  this.pickerName = '工程名称'
        this.getProjectName()
        this.showSelectProject = true
		  }else if( type === 'siteName'){
			  this.pickerName = '站点名称'
        if(this.engName === '') {
          Dialog.alert({
            message: "请先选择工作名称",
            theme: "round-button"
          });
        }else {
          this.getSiteName()
          this.showSelectSite = true;
        }
		  }else if( type === 'scene'){
			  this.pickerName = '施工现场'
        if(this.engName === '') {
          Dialog.alert({
            message: "请先选择工作名称",
            theme: "round-button"
          });
        }else if(this.siteName === '') {
          Dialog.alert({
            message: "请先选择站点名称",
            theme: "round-button"
          });
        }else {
          this.showPicker = true
        }

		  }
	  },
	  onConfirm(value){
      this.engName  = value.text
      this.engId = value.value
      this.siteName = ''
      this.showSelectProject = false
	  },
    onConfirmSite(value) {
      this.siteName = value.text
      this.siteId = value.value
      this.getSceneName()
      this.showSelectSite = false
    },
    onConfirmfiled(value) {
      if(value.text === '请填写') {
        this.sceneColumns = []
        this.sceneName = ''
        this.sceneId = ''
        this.showPicker = false
      }else {
        this.sceneName = value.text
        this.sceneId = value.value
        this.showPicker = false
      }
    },
    imageHandle(imgIndex, imgItem, handleType) {
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgIndex, imgItem)
      } else if (handleType === 'PREVIEW') {
        this.files = [imgItem]
        this.showPreview = true
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          title: `是否确认删除`
        })
            .then(() => {
              this.$set(this.fileList, imgIndex, {
                    ...this.fileList,
                    File: null,
                    img: '',
                    fl: '5'
                  })
              let nullCount = 0;
              this.fileList = this.fileList.filter( item => {
                if(item.File !== null) {
                  return true
                }else if(item.File === null && nullCount === 0) {
                  nullCount++;
                  return true
                }else {
                  return false
                }
              })
              console.log(this.fileList,'323232')
              this.files = imgItem
            })
            .catch(() => {
            })
      }
    },
    choosePhoto(imgIndex, imgItem) {
      let _this = this
      wx.chooseImage({
        count: 1,
        sourceType: ['album','camera'],
        success: chooseImageRes => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
              const localData = res.localData
              let imageBase64 = ''
              if (localData.indexOf('data:image') == 0) {
                //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                imageBase64 = localData
              } else {
                //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                imageBase64 =
                    'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
              }
              const photoName = `${new Date().getTime()}`

                _this.$set(_this.fileList, imgIndex, {
                  File: _this.dataURLtoFile(imageBase64,`${photoName}.jpeg`),
                  img: imageBase64,
                  fl: '5',
                })

                // console.log('cccc', _this.dataURLtoFile(imageBase64,`${photoName}.jpeg`))
              if(_this.fileList[_this.fileList.length - 1].File !== null) {
                _this.fileList.push({
                  File: null,
                  img: '',
                  fl: '5',
                })
              }
            }
          })
        },
        fail: error => {}
      })
    },
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
  }
};
</script>
<style scoped lang="scss">
/deep/.epgis-logo {
  display: none;
}
/deep/.epgis-ctrl-scale2 {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
}
.task-monitor-main {
  width: 100vw;
	height: 100vh;
	background: #F2F6FA;
  overflow: hidden;
	.spot-content{
    width: calc(100vw - #{px2vw(60)});
    height: calc(100vh - #{px2vh(380)});
    margin: px2vh(30);
    background: #F2F6FA;
    overflow: auto;
    .basic-info {
      height: auto;
      margin-bottom: px2vh(50);
    }
    .map-content {
      height: px2vh(780);
      background: #fff;
      margin-bottom: px2vh(30);
      border-radius: px2vh(20) px2vw(20);
      .map-top {
        height: px2vh(42);
        display: flex;
        padding: px2vh(64) px2vw(50);
        text {
          flex: 1;
          color: #666;
          font-size: px2vh(42);
        }
        .orientation {
          color: #417ADC;
          text-align: right;
        }
      }
      #map_holder {
        width: calc(100vw - #{px2vw(160)});
        margin-left: px2vw(50);
        height: px2vh(560);
      }
    }
    .plate-title {
      margin-bottom: px2vh(30);
    }
    .overall-materials {
      width: 100%;
      display: flex;
      background: #fff;
      margin-bottom: px2vh(30);
      .image-list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        padding-top: px2vh(49);
        box-sizing: border-box;
        img {
          width: px2vw(230);
          height: px2vw(230);
          border-radius: px2vw(6);
        }
        .upload-button {
          width: px2vw(230);
          height: px2vw(230);
          flex-shrink: 0;
          position: relative;
          background-image: url('../../../static/controlImg/bg_pz.png');
          background-size: 100% px2vw(230);
          margin: 0 calc((100% - #{px2vw(690)}) / 6) px2vh(45) calc((100% - #{px2vw(690)}) / 6);
          .delete-icon {
            position: absolute;
            top: px2vw(-20);
            right: px2vw(-20);
            width: px2vw(40);
            height: px2vw(40);
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 50%;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
	}
	footer {
    width: calc(100% - #{px2vw(60)});
    margin-left: px2vw(30);
    height: px2vh(180);
    border-top:px2vh(1) solid #E5E5E5;
    box-sizing:border-box;
    padding-top: px2vh(16);
		/deep/ .van-button {
			width: calc(100% - #{px2vw(60)});
			margin-left: px2vh(30);
			height: px2vh(120);
			color: #fff;
			background-color: #417ADC;
			border: 1px solid #417ADC;
			border-radius: px2vh(60);
		}
	}

}
.van-preview-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;

  .van-swipe {
    width: 100%;
    height: 60%;

    .van-swipe-item {
      display: flex;
      align-items: center;

      img {
        width: 100%;
      }
    }
  }
}
.circle-wrap {
  width: 100%;
  height: px2vh(600);
  display: flex;
  align-items: center;
  justify-content: center;
  .circle-conent {
    width: px2vw(400);
    height: px2vh(340);
    line-height: px2vh(340);
    background-color: #417ADC;
    border-radius: 50%;
    color: #fff;
    font-size: 18px;
    text-align: center;
    box-shadow: 0 0 10px #417ADC;
  }
}
</style>
